<?php

namespace app\Modules\Api\models;

use Yii;
use app\models\Product as BaseModel;
use yii\helpers\ArrayHelper;

/**
 * LoginForm is the model behind the login form.
 *
 * @property user|null $user This property is read-only.
 *
 */
class Product extends BaseModel
{
    public function fields()
    {
        $fields = parent::fields();
        $strvalfields = [
            'pid',
            'type_id',
            'name',
            'hot',
            'market_val',
            'cost',
            'return_rate',
            'start_price',
            'scope',
            'fee',
            'degree',
            'lowest_price',
            'highest_price',
            'actcount',
            'reacount',
            'can_robot',
            'have_cost',
            'ios',
            'can_give',
            'kind',
            'can_show',
            'state'
        ];

        foreach($strvalfields as $strvalfield){
            $fields[$strvalfield] = function() use ($strvalfield){
                return strval($this->$strvalfield);
            };
        }
        unset($fields['created_at'],$fields['updated_at']);
        return $fields;
    }

    public function extraFields(){
        return [
            'first_pic'=>function(){
                $pics = $this->pics;
                $pic =  $pics?$pics[0]['url']:'default_photo.jpg';
                return \Yii::$app->params['uploadUrl'].$pic;
            },
            'pics',
        ];
    }

    public function collectOrNot(User $user)
    {
        $hasCollect = self::hasCollect($this->pid,$user->userid);
        //查看是否收藏
        if($hasCollect) {
            $user->unlink('collects',$this,true);
            $isLink = false;
        }else{
            $user->link('collects',$this);
            $isLink = true;
        }
        return $isLink;
    }

    public static function hasCollect($product_id,$user_id){
        $collect = Product::find()
            ->innerJoin('collect','product.pid = collect.product_id')
            ->where(['collect.product_id'=>$product_id,'collect.user_id'=>$user_id])
            ->one();
        return boolval($collect);
    }

    /**
     * 获取产品数组
     * @return self[]
     */
    public static function getProductObjects()
    {
        $key = 'getProductObjects';
        if (!Yii::$container->has($key)) {
            $stdClass = new \stdClass();
            $stdClass->objects = self::find()->orderBy(['pid'=>SORT_DESC])->indexBy('pid')->all();
            Yii::$container->set($key, $stdClass);
        }
        $data = Yii::$container->get($key)->objects;
        return $data;
    }

    /**
     * 获取用户的收藏产品id数组
     * @param $user_id
     * @return mixed
     */
    public static function getIsCollects($user_id)
    {
        $key = 'getIsCollects';
        if (!Yii::$container->has($key)) {
            $stdClass = new \stdClass();
            $stdClass->objects = ArrayHelper::getColumn(Product::find()
                ->innerJoin('collect','product.pid = collect.product_id')
                ->where(['collect.user_id'=>$user_id])
                ->select(['pid'])
                ->asArray()
                ->all(),'pid');
            Yii::$container->set($key, $stdClass);
        }
        $data = Yii::$container->get($key)->objects;
        return $data;
    }

    /**
     * 获取产品信息
     * @param $pid
     * @param int $user_id
     * @param Auction|null $auction
     * @return array|\stdClass
     */
    public static function getProduct($pid,$user_id = 0,Auction $auction=null)
    {
        $product_fields = ['pid','name','type_id','spec'];
        $product_extraFields = ['first_pic'];
        $product_objects = Product::getProductObjects();
        $product = isset($product_objects[$pid])
            ? $product_objects[$pid]->toArray($product_fields,$product_extraFields):[];
        if(!$auction){
            $first_auctions = Auction::getFirsts();
            if(!isset($first_auctions[$pid])){
                return new \stdClass();
            }
            $first_auction = $first_auctions[$pid];
        }else{
            $first_auction = $auction;
        }
        /** @var  $topRcd BidRcd*/
        $topRcd = BidRcd::find()->where(['auction_id'=>$first_auction->auctionid])->orderBy(['created_at'=>SORT_DESC])->one();
        $product['username'] = $topRcd?$topRcd->name:'';
        $product['first_auction'] = $first_auction->toArray(['actcount','reacount','price','state']);
        $product['auction_id'] = strval($first_auction->auctionid);
        $collects = Product::getIsCollects($user_id);
        $product['is_like'] = in_array($pid,$collects)?'1':'0';
        return $product;
    }
}